package com.hanbang.taitaigou.ui.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.LayoutParams;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.hanbang.taitaigou.R;
import com.hanbang.taitaigou.model.BannerAdData;
import com.hanbang.taitaigou.utils.http.HttpLocalUtils;
import com.hanbang.taitaigou.utils.other.ObjectUtils;

import org.xutils.ImageManager;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class BannerAdAdapter extends PagerAdapter implements
        OnPageChangeListener {

    private Context context = null;
    private ArrayList<ImageView> list = new ArrayList<ImageView>();
    private ArrayList<BannerAdData> data = null;
    private RadioGroup dotLayout = null;
    private RelativeLayout root = null;
    private ImageManager imageManager = x.image();
    private ViewPager viewPager = null;
    private int time = 1000 * 5;
    private OnItemClickListener onItemClickListener = null;
    ImageOptions imageOptions = new ImageOptions.Builder()
            .setImageScaleType(ScaleType.CENTER_CROP)
//            .setLoadingDrawableId(R.mipmap.ic_launcher)
//            .setFailureDrawableId(R.mipmap.ic_launcher)
            .build();

    public BannerAdAdapter(Context context, RelativeLayout root,
                           ArrayList<BannerAdData> data) {


        this.data = data;
        this.root = root;
        this.context = context;
        this.dotLayout = (RadioGroup) ((LinearLayout) root.getChildAt(1))
                .getChildAt(0);
        this.viewPager = (ViewPager) root.getChildAt(0);
        viewPager.setAdapter(this);
        // pager翻页
        viewPager.setOnPageChangeListener(this);
        if (data.size() > 0) {
            notifyDataSetChanged();
        }
        setWidthAndHeight(16, 9);
    }








    /*
     * 设置宽高比 16：9 默认16：9
     */
    @SuppressWarnings("deprecation")
    public void setWidthAndHeight(int width, int height) {
        ViewGroup.LayoutParams params = viewPager.getLayoutParams();
        params.height = (int) Math.rint(((Activity) context).getWindowManager()
                .getDefaultDisplay().getWidth()
                * height / (width * 1.0));
        viewPager.setLayoutParams(params);
    }

    private Timer timer = new Timer();
    private MyTimerTask task = null;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 123) {
                if (data.size() > 1) {
                    viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
                }
            }
        }
    };

    public int getCurrentItem() {
        return viewPager.getCurrentItem();
    }

    public ImageView getCurrentItemView() {
        return list.get(viewPager.getCurrentItem());
    }

    public void start() {
        stop();
        task = new MyTimerTask();
        timer.schedule(task, time, time);
    }

    private class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            handler.sendEmptyMessage(123);
        }

    }

    public void stop() {
        if (task != null) {
            task.cancel();
        }
    }

    @Override
    public void notifyDataSetChanged() {
        LayoutParams params = new LayoutParams();
        params.width = LayoutParams.MATCH_PARENT;
        params.height = LayoutParams.MATCH_PARENT;
        RadioGroup.LayoutParams params2 = new RadioGroup.LayoutParams(
                ObjectUtils.dip2px(context, 8), ObjectUtils.dip2px(context, 8));
        params2.setMargins(0, 0, ObjectUtils.dip2px(context, 4), 0);
        dotLayout.removeAllViews();
        list.clear();
        for (int i = 0; i < data.size(); i++) {
            // 设置图片
            ImageView image = new ImageView(context);
            image.setScaleType(ScaleType.CENTER_CROP);
            image.setLayoutParams(params);
            list.add(image);
            image.setTag(data.get(i));
            image.setOnClickListener(new MyOnClickListener(i));
            // 设置圆点
            RadioButton view = new RadioButton(context);
            view.setLayoutParams(params2);
            view.setBackgroundResource(R.drawable.dot_focus);
            view.setButtonDrawable(R.drawable.dot_focus);
            view.setClickable(false);
            dotLayout.addView(view);
        }
        if (list.size() > 1) {
            // 设置图片
            ImageView image = new ImageView(context);
            image.setScaleType(ScaleType.CENTER_CROP);
            image.setLayoutParams(params);
            list.add(0, image);
            // 设置图片
            image = new ImageView(context);
            image.setScaleType(ScaleType.CENTER_CROP);
            image.setLayoutParams(params);
            list.add(image);
        }
        if (data.size() == 0) {
            root.setVisibility(View.GONE);
        } else {
            root.setVisibility(View.VISIBLE);
        }
        super.notifyDataSetChanged();
        if (list.size() != 0) {
            viewPager.setCurrentItem(1);
            onPageSelected(1);
        }
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return (arg0 == arg1);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        position = position % list.size();
        container.removeView(list.get(position));
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        position = position % list.size();
        ImageView image = list.get(position);
        String uri = "";

        if (position == list.size() - 1) {
            uri = HttpLocalUtils.getHttpFileUrl(data.get(0).getImg_url());
        } else if (position == 0) {
            uri = HttpLocalUtils.getHttpFileUrl(data.get(data.size() - 1)
                    .getImg_url());
        } else {
            uri = HttpLocalUtils.getHttpFileUrl(data.get(position - 1)
                    .getImg_url());
        }
        x.image().bind(image, uri,imageOptions,null);
        container.addView(list.get(position));// 添加页卡
        return list.get(position);
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int arg0) {
        if (list.size() > 1) {
            if (arg0 == list.size() - 1) {
                viewPager.setCurrentItem(1, false);
            } else if (arg0 == 0) {
                viewPager.setCurrentItem(list.size() - 2, false);
            } else if (arg0 > 0) {
                ((RadioButton) dotLayout.getChildAt(arg0 - 1)).setChecked(true);
            }
        } else {
            ((RadioButton) dotLayout.getChildAt(0)).setChecked(true);
        }
    }

    private class MyOnClickListener implements OnClickListener {

        int position = -1;

        public MyOnClickListener(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            if (onItemClickListener != null) {
                onItemClickListener.onItemClick(v, position);
            }
        }

    }

    public interface OnItemClickListener {
        public void onItemClick(View v, int position);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
}
